package cn.remex.core.util.email;

import cn.remex.RemexConstants;
import cn.remex.core.exception.ServiceCode;
import cn.remex.core.util.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

/**
 * Created by guoqi on 2016/10/30.
 */
public class EmailHelper {

    static Logger logger = LoggerFactory.getLogger(EmailHelper.class);
    public static class EmailBuilder {
        private String smtpHost;//邮件服务器
        private String user;//用户密码
        private String password;//用户密码
        private boolean smtpAuth = true; //验证
        private int smtpTimeout = 25000; //超时
        private boolean smtpStarttls = true; //默认true
        private String encode = "UTF-8"; //默认true
        private String fromEmail;//发件邮箱
        private String toEmail;//收件邮箱
        private String ccEmail;//抄送邮箱
        private String title;//标题
        private Object content;//内容


        public EmailBuilder() {
        }
        public EmailBuilder toEmail(String toEmail){
            this.toEmail=toEmail;return this;
        }
        public EmailBuilder ccEmail(String ccEmail){
            this.ccEmail=ccEmail;return this;
        }
        public EmailBuilder title(String title){
            this.title=title;return this;
        }
        public EmailBuilder content(Object content){
            this.content=content;return this;
        }


        public EmailBuilder stmpHost(String emailHost) {
            this.smtpHost = emailHost;
            return this;
        }


        public EmailBuilder fromEmail(String fromEmail) {
            this.fromEmail = fromEmail;return this;
        }


        public EmailBuilder password(String password) {
            this.password = password;return this;
        }


        public EmailBuilder smtpAuth(boolean smtpAuth) {
            this.smtpAuth = smtpAuth;return this;
        }


        public EmailBuilder smtpTimeout(int smtpTimeout) {
            this.smtpTimeout = smtpTimeout;return this;
        }


        public EmailBuilder smtpStarttls(boolean smtpStarttls) {
            this.smtpStarttls = smtpStarttls;return this;
        }


        public EmailBuilder encode(String encode) {
            this.encode = encode;return this;
        }

        public EmailBuilder user(String user){
            this.user=user;return this;
        }


        public boolean send(){
            try {
                EmailHelper.sendEmail(this);
                return true;
            } catch (Exception e) {
                logger.info("发送邮件失败，内容{}",this);
                return false;
            }
        }
    }
    public static EmailBuilder createEmail(){
        return new EmailBuilder();
    }
    
    private static void sendEmail(EmailBuilder emailBuilder) throws Exception {
//        String fromMail, String toEmail, String mailTitle, String mailContent, String user, String passwor
        Properties props = new Properties(); //可以加载一个配置文件  
        // 使用smtp：简单邮件传输协议  
        props.put("mail.smtp.host", "smtp.exmail.qq.com");//存储发送邮件服务器的信息  
        props.put("mail.smtp.auth", "true");//同时通过验证  
        Session session = Session.getInstance(props);//根据属性新建一个邮件会话  
        MimeMessage message = new MimeMessage(session);//由邮件会话新建一个消息对象  
        message.setFrom(new InternetAddress(emailBuilder.fromEmail));//设置发件人的地址
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailBuilder.toEmail));//设置收件人,并设置其接收类型为TO
        message.setSubject(emailBuilder.title);//设置标题
        //设置信件内容  
        //message.setText(mailContent); //发送 纯文本 邮件 todo  
        message.setContent(emailBuilder.content, "text/html;charset=UTF-8"); //发送HTML邮件，内容样式比较丰富
        message.setSentDate(new Date());//设置发信时间  
        message.saveChanges();//存储邮件信息  
        //发送邮件  
        Transport transport = session.getTransport("smtp");
        transport.connect(emailBuilder.user, emailBuilder.password);
        transport.sendMessage(message, message.getAllRecipients());//发送邮件,其中第二个参数是所有已设好的收件人地址  
        transport.close();
        session=null;
        message =null;
    }
    
    
    
    ///邮件发送服务器
    private static JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
    /**
     * 安全认证设置
     */
    private Properties safetyProperties = new Properties();

    private EmailSetings emailSetings;

    //邮件服务器
    private static final String EMAIL_HOST_KEY = "mail.host";
    // 用户名
    private static final String EMAIL_USERNAME_KEY = "mail.username";
    //用户密码
    private static final String EMAIL_PASSWORD_KEY = "mail.password";
    /**
     * 接收人
     */
//    private static final String EMAIL_TO_KEY = "mail.to";
//    /**发送人*/
//    private static final String EMAIL_FROM_KEY = "mail.from";
    //服务器进行认证,认证用户名和密码是否正确
    private static final String EMAIL_SMTP_AUTH_KEY = "mail.smtp.auth";

    // 超时时间设定
    private static final String EMAIL_SMTP_TIMEOUT_KEY = "mail.smtp.timeout";

    private static final String EMAIL_SMTP_HOST = "mail.smtp.host";
    //编码设置
    private static final String EMAIL_ENCODING_KEY = "mail.encoding";
    // TLS认证的时候需要设置
    private static final String EMAIL_SMTP_STARTTLS_KEY = "mail.smtp.starttls.enable";
    private static final String EMAIL_SMTP_SSL_TRUST = "mail.smtp.ssl.trust";
    //private static final String EMAIL_SMTP_SOCKETFACTORY_CLASS_KEY = "mail.smtp.socketFactory.class";
    //public static final String EMAIL_SMTP_SOCKETFACTORY_CLASS = ReadConfigEmail.getPropertyByKey(EMAIL_SMTP_SOCKETFACTORY_CLASS_KEY);
    //pcmtesohkhdlbhcg
    public EmailHelper(EmailSetings emailSetings) {
        Assert.notNullAndEmpty(emailSetings.getEmailHost(), ServiceCode.FAIL, "邮箱设置错误缺少参数！");
        Assert.notNullAndEmpty(emailSetings.getEmailUserName(), ServiceCode.FAIL, "邮箱设置错误缺少参数！");
        Assert.notNullAndEmpty(emailSetings.getEmailPassword(), ServiceCode.FAIL, "邮箱设置错误缺少参数！");
        this.emailSetings = emailSetings;
        //调试信息,可以取消
//        //System.setProperty( "javax.net.debug", "ssl");
//        safetyProperties.put("javax.net.debug", "ssl");
        safetyProperties.put(EMAIL_SMTP_HOST, "smtp.exmail.qq.com");
        safetyProperties.put(EMAIL_SMTP_AUTH_KEY, emailSetings.isEmailSmtpAuth());
        safetyProperties.put(EMAIL_SMTP_TIMEOUT_KEY, emailSetings.getEmailSmtpTimeout());
        safetyProperties.put(EMAIL_SMTP_STARTTLS_KEY, emailSetings.isEmailSmtpStarttls());
        safetyProperties.put(EMAIL_ENCODING_KEY, emailSetings.getEmailEncode());
        safetyProperties.put(EMAIL_SMTP_SSL_TRUST, emailSetings.getEmailHost());

        //safetyProperties.put(EMAIL_SMTP_SOCKETFACTORY_CLASS_KEY, EMAIL_SMTP_SOCKETFACTORY_CLASS);
        senderImpl.setHost(emailSetings.getEmailHost());
        senderImpl.setUsername(emailSetings.getEmailUserName());
        senderImpl.setPassword(emailSetings.getEmailPassword());
//        senderImpl.setPort();
        senderImpl.setJavaMailProperties(safetyProperties);
        senderImpl.getSession().setDebug(true);
    }
    /**
     * 默认为发送文本类型
     * */
    public MailMessageFactory createMailMessage(){
        return new MailMessageFactory(this);
    }

    /**
     * 请显示指明文件类型为：TEXT,HTML,默认为文本类型
     *
     * */
    public MailMessageFactory createMailMessage(SendMailType sendMailType){
        return new MailMessageFactory(this,sendMailType);
    }

    public JavaMailSenderImpl getSenderImpl() {
        return senderImpl;
    }

    protected Properties getSafetyProperties() {
        return safetyProperties;
    }

    protected EmailSetings getEmailSetings() {
        return emailSetings;
    }
}
